package app

import (
	"ams/global"
	"fmt"
	"github.com/urfave/cli/v2"
	"os"
	"time"
)

const (
	cliName       = "miao_ams"
	cliUsage      = "资产管理系统(Miao Asset Management System)"
	appConfig     = "config_ams"
	httpApiPrefix = "/api/ams" // http服务的api前缀
	Version       = "1.0.0"
)

func Run() (err error) {
	global.InitConfig(appConfig)
	// 创建服务对象
	appServ, err := NewService()
	if err != nil {
		return err
	}
	app := cli.NewApp()
	app.Name = cliName
	app.Version = fmt.Sprintf("%s build:%s", Version, time.Now().Format("20060102_15:04:05"))
	app.Usage = cliUsage
	app.Commands = []*cli.Command{
		{
			Name:   "install",
			Usage:  "Install the service",
			Action: func(c *cli.Context) error { return appServ.Install() },
		},
		{
			Name:   "uninstall",
			Usage:  "Uninstall the service",
			Action: func(c *cli.Context) error { return appServ.Uninstall() },
		},
		{
			Name:   "start",
			Usage:  "start the service",
			Action: func(c *cli.Context) error { return appServ.Start() },
		},
		{
			Name:   "stop",
			Usage:  "stop the service",
			Action: func(c *cli.Context) error { return appServ.Stop() },
		},
		{
			Name:   "run",
			Usage:  "run the service",
			Action: func(c *cli.Context) error { return appServ.Run() },
		},
	}
	// 运行服务,如果没有这个逻辑，服务启动时会提示：1053，-The service did not respond to the start or control request in a timely fashion
	// 这个是多轮测试的结果，测试了很多次。
	// 原理未知. 猜测是 Run() 会通知windows调用sysCall启动服务，而注册服务时是没有参数的，此时的 os.Args 第一个参数是程序本身，没有第二个参数，
	// ps : os.Args = [C:\01Code\demo\api-test\go_build_api_test.exe start] ,并不是我们理解的 go_build_api_test.exe 是程序，start 是参数。第一个参数永远是程序本身
	// 如果不能触发 s.Run()，windows就无法收到 sysCall 的启动信号，因此提示 1053.
	if len(os.Args) == 1 {
		err = appServ.Run()
		if err != nil {
			return err
		}
	}
	if err = app.Run(os.Args); err != nil {
		return err
	}
	return
}
